{% extends "base.html" %}

{% block title %}XBot管理后台 - 好友列表{% endblock %}

{% block page_title_icon %}<i class="bi bi-person page-title-icon"></i>{% endblock %}
{% block page_title %}好友列表{% endblock %}

{% block content %}
<!-- 操作区域 -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="input-group">
            <input type="text" class="form-control" placeholder="搜索好友..." id="searchInput">
            <button class="btn btn-primary" type="button" id="searchBtn">
                <i class="bi bi-search"></i> 搜索
            </button>
        </div>
    </div>
    <div class="col-md-4 text-end">
        <button class="btn btn-primary" id="refreshBtn">
            <i class="bi bi-arrow-clockwise"></i> 刷新列表
        </button>
    </div>
</div>

<!-- 好友统计卡片 -->
<div class="row mb-4">
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-primary-light">
                    <i class="bi bi-people text-primary"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">总好友数</div>
                    <div class="fw-bold fs-4" id="totalFriends">--</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-success-light">
                    <i class="bi bi-person-check text-success"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">在线好友</div>
                    <div class="fw-bold fs-4" id="onlineFriends">--</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-info-light">
                    <i class="bi bi-clock-history text-info"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">最近更新</div>
                    <div class="fw-bold" id="lastUpdate">--</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 好友列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">好友列表</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>头像</th>
                        <th>昵称</th>
                        <th>微信ID</th>
                        <th>备注</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="friendsTableBody">
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2 text-muted">加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 好友详情模态框 -->
<div class="modal fade" id="friendDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">好友详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="friendDetailContent">
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="mt-2">加载中...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="editRemarkBtn">编辑备注</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑备注模态框 -->
<div class="modal fade" id="editRemarkModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑好友备注</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="editRemarkWxid">
                <div class="mb-3">
                    <label for="remarkInput" class="form-label">备注名称</label>
                    <input type="text" class="form-control" id="remarkInput" placeholder="请输入备注名称">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveRemarkBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 发送消息模态框 -->
<div class="modal fade" id="sendMessageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">发送消息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="sendMessageWxid">
                <div class="mb-3">
                    <label class="form-label">发送给：<span id="sendMessageRecipient" class="fw-bold"></span></label>
                </div>
                <div class="mb-3">
                    <label for="messageContent" class="form-label">消息内容</label>
                    <textarea class="form-control" id="messageContent" rows="5" placeholder="请输入消息内容"></textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">消息类型</label>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="messageType" id="messageTypeText" value="1" checked>
                        <label class="form-check-label" for="messageTypeText">
                            文本消息
                        </label>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="sendMessageBtn">
                    <i class="bi bi-send"></i> 发送
                </button>
            </div>
        </div>
    </div>
</div>

{% block scripts %}
<script>
// 全局变量
let friendsList = [];
let currentFriend = null;
let friendDetailModal = null;
let editRemarkModal = null;
let sendMessageModal = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化模态框
    friendDetailModal = new bootstrap.Modal(document.getElementById('friendDetailModal'));
    editRemarkModal = new bootstrap.Modal(document.getElementById('editRemarkModal'));
    sendMessageModal = new bootstrap.Modal(document.getElementById('sendMessageModal'));
    
    // 加载好友列表
    loadFriends();
    
    // 绑定事件
    document.getElementById('refreshBtn').addEventListener('click', loadFriends);
    document.getElementById('searchBtn').addEventListener('click', searchFriends);
    document.getElementById('searchInput').addEventListener('keyup', function(e) {
        if (e.key === 'Enter') {
            searchFriends();
        }
    });
    
    document.getElementById('editRemarkBtn').addEventListener('click', showEditRemarkModal);
    document.getElementById('saveRemarkBtn').addEventListener('click', saveRemark);
    document.getElementById('sendMessageBtn').addEventListener('click', sendMessage);
});

// 加载好友列表
async function loadFriends() {
    const tableBody = document.getElementById('friendsTableBody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="6" class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2 text-muted">加载中...</p>
            </td>
        </tr>
    `;
    
    try {
        const response = await fetch('/api/friends');
        const data = await response.json();
        
        if (data.success) {
            friendsList = data.data || [];
            displayFriends(friendsList);
            updateStats(friendsList);
        } else {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center py-4">
                        <div class="text-danger">
                            <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                            <p>加载失败: ${data.message || '未知错误'}</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载好友列表失败:', error);
        tableBody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4">
                    <div class="text-danger">
                        <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                        <p>加载失败: ${error.message || '网络错误'}</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

// 显示好友列表
function displayFriends(friends) {
    const tableBody = document.getElementById('friendsTableBody');
    
    if (!friends || friends.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4">
                    <div class="text-muted">
                        <i class="bi bi-people fs-3 mb-3"></i>
                        <p>暂无好友数据</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    let html = '';
    friends.forEach(friend => {
        const wxid = friend.wxid?.string || friend.wxid || '';
        const nickname = friend.nickname?.string || friend.nickname || '未知';
        const remark = friend.remark?.string || friend.remark || '--';
        
        html += `
            <tr>
                <td>
                    <div class="avatar-circle bg-primary text-white">
                        ${nickname[0]?.toUpperCase() || 'U'}
                    </div>
                </td>
                <td>${escapeHtml(nickname)}</td>
                <td><small class="text-muted">${escapeHtml(wxid)}</small></td>
                <td>${escapeHtml(remark)}</td>
                <td>
                    <span class="badge bg-success">在线</span>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary me-1" onclick="viewFriendDetail('${wxid}')">
                            <i class="bi bi-info-circle"></i> 详情
                        </button>
                        <button class="btn btn-outline-secondary me-1" onclick="showEditRemarkModal('${wxid}', '${remark}')">
                            <i class="bi bi-pencil"></i> 备注
                        </button>
                        <button class="btn btn-outline-success" onclick="showSendMessageModal('${wxid}', '${escapeHtml(nickname)}')">
                            <i class="bi bi-chat-dots"></i> 发消息
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = html;
}

// 更新统计信息
function updateStats(friends) {
    document.getElementById('totalFriends').textContent = friends.length;
    document.getElementById('onlineFriends').textContent = friends.length; // 假设全部在线
    document.getElementById('lastUpdate').textContent = new Date().toLocaleString();
}

// 搜索好友
function searchFriends() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    
    if (!searchTerm) {
        displayFriends(friendsList);
        return;
    }
    
    const filteredFriends = friendsList.filter(friend => {
        const nickname = (friend.nickname?.string || friend.nickname || '').toLowerCase();
        const wxid = (friend.wxid?.string || friend.wxid || '').toLowerCase();
        const remark = (friend.remark?.string || friend.remark || '').toLowerCase();
        
        return nickname.includes(searchTerm) || wxid.includes(searchTerm) || remark.includes(searchTerm);
    });
    
    displayFriends(filteredFriends);
}

// 查看好友详情
async function viewFriendDetail(wxid) {
    const detailContent = document.getElementById('friendDetailContent');
    detailContent.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2">加载中...</p>
        </div>
    `;
    
    // 保存当前好友ID
    currentFriend = wxid;
    
    // 显示模态框
    friendDetailModal.show();
    
    try {
        const response = await fetch(`/api/friends/${wxid}`);
        const data = await response.json();
        
        if (data.success) {
            const friend = data.data;
            const nickname = friend.nickname?.string || friend.nickname || '未知';
            const remark = friend.remark?.string || friend.remark || '--';
            
            let html = `
                <div class="text-center mb-4">
                    <div class="avatar-circle mx-auto bg-primary text-white" style="width: 80px; height: 80px; font-size: 2rem;">
                        ${nickname[0]?.toUpperCase() || 'U'}
                    </div>
                    <h4 class="mt-3">${escapeHtml(nickname)}</h4>
                    <p class="text-muted">${escapeHtml(wxid)}</p>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">备注名</div>
                        <div>${escapeHtml(remark)}</div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">性别</div>
                        <div>${friend.gender === 1 ? '男' : friend.gender === 2 ? '女' : '未知'}</div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">地区</div>
                        <div>${escapeHtml(friend.country || '')} ${escapeHtml(friend.province || '')} ${escapeHtml(friend.city || '')}</div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">签名</div>
                        <div>${escapeHtml(friend.signature || '--')}</div>
                    </div>
                </div>
            `;
            
            detailContent.innerHTML = html;
        } else {
            detailContent.innerHTML = `
                <div class="text-center text-danger">
                    <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                    <p>加载失败: ${data.message || '未知错误'}</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载好友详情失败:', error);
        detailContent.innerHTML = `
            <div class="text-center text-danger">
                <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                <p>加载失败: ${error.message || '网络错误'}</p>
            </div>
        `;
    }
}

// 显示编辑备注模态框
function showEditRemarkModal(wxid, remark) {
    if (wxid) {
        document.getElementById('editRemarkWxid').value = wxid;
        document.getElementById('remarkInput').value = remark !== '--' ? remark : '';
    } else {
        document.getElementById('editRemarkWxid').value = currentFriend;
        document.getElementById('remarkInput').value = '';
    }
    
    // 隐藏好友详情模态框
    if (friendDetailModal._isShown) {
        friendDetailModal.hide();
    }
    
    // 显示编辑备注模态框
    editRemarkModal.show();
}

// 保存备注
async function saveRemark() {
    const wxid = document.getElementById('editRemarkWxid').value;
    const remark = document.getElementById('remarkInput').value;
    
    if (!wxid) {
        alert('好友ID不能为空');
        return;
    }
    
    try {
        const response = await fetch(`/api/friends/${wxid}/remark`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ remark })
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 隐藏编辑备注模态框
            editRemarkModal.hide();
            
            // 刷新好友列表
            loadFriends();
            
            // 如果当前好友详情模态框是打开的，刷新详情
            if (currentFriend === wxid) {
                viewFriendDetail(wxid);
            }
        } else {
            alert(`设置备注失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('设置备注失败:', error);
        alert(`设置备注失败: ${error.message || '网络错误'}`);
    }
}

// 显示发送消息模态框
function showSendMessageModal(wxid, nickname) {
    document.getElementById('sendMessageWxid').value = wxid;
    document.getElementById('sendMessageRecipient').textContent = nickname || wxid;
    document.getElementById('messageContent').value = '';
    
    // 显示发送消息模态框
    sendMessageModal.show();
}

// 发送消息
async function sendMessage() {
    const wxid = document.getElementById('sendMessageWxid').value;
    const content = document.getElementById('messageContent').value;
    const msgType = parseInt(document.querySelector('input[name="messageType"]:checked').value) || 1;
    
    if (!wxid) {
        alert('好友ID不能为空');
        return;
    }
    
    if (!content) {
        alert('消息内容不能为空');
        return;
    }
    
    try {
        // 显示发送中状态
        const sendBtn = document.getElementById('sendMessageBtn');
        const originalBtnText = sendBtn.innerHTML;
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 发送中...';
        
        const response = await fetch('/api/message/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                to_wxid: wxid,
                content: content,
                msg_type: msgType
            })
        });
        
        const data = await response.json();
        
        // 恢复按钮状态
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalBtnText;
        
        if (data.success) {
            // 关闭模态框
            sendMessageModal.hide();
            
            // 显示成功提示
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-success alert-dismissible fade show';
            alertDiv.role = 'alert';
            alertDiv.innerHTML = `
                <i class="bi bi-check-circle-fill me-2"></i> 消息发送成功
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            document.querySelector('.content-container').insertBefore(alertDiv, document.querySelector('.content-container').firstChild);
            
            // 3秒后自动关闭
            setTimeout(() => {
                const bsAlert = new bootstrap.Alert(alertDiv);
                bsAlert.close();
            }, 3000);
        } else {
            alert(`发送消息失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('发送消息失败:', error);
        alert(`发送消息失败: ${error.message || '网络错误'}`);
    }
}

// 转义HTML
function escapeHtml(text) {
    if (!text) return '';
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
</script>

<style>
.avatar-circle {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
}

.icon-wrapper {
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 1.5rem;
}

.bg-primary-light {
    background-color: rgba(67, 97, 238, 0.1);
}

.bg-success-light {
    background-color: rgba(16, 185, 129, 0.1);
}

.bg-info-light {
    background-color: rgba(59, 130, 246, 0.1);
}
</style>
{% endblock %}
{% endblock %} 